<template>
	<div>
		<el-form label-width="100px">
			<template v-if="operation == '添加'">
				<el-form-item label="上级编码">
					<span>{{ parentNode.ItemCode }}</span>
				</el-form-item>
				<el-form-item label="本级编码">
					<el-input v-model="curCode" />
				</el-form-item>
			</template>
			<el-form-item v-if="operation == '添加'" label="节点编码">
				<span>{{ parentNode.ItemCode + curCode }}</span>
			</el-form-item>
			<el-form-item v-else label="节点编码">
				<span>{{ curNode.ItemCode }}</span>
			</el-form-item>
			<!-- <el-form-item label="名称"> -->
			<el-form-item :label="parentNode.Title">
				<el-input v-model="curNodeTmp.Title" />
			</el-form-item>
			<el-form-item label="设置图标">
				<el-row style="display: flex">
					<i v-if="/^el-.+/.test(curNode.IconID)" :class="curNode.IconID" style="font-size: 24px" />
					<img v-else-if="/^http.+/.test(curNode.IconID)" :src="curNode.IconID" style="width: 30px" />
					<el-button type="primary" @click="iconsVisible = true" style="margin: 0 10px">选择图标</el-button>
					<zUpload style="width: 300px" ref="zupload" :attrs="attrs" v-model="curNodeTmp.IconID" :showPlusIcon="false">
						<el-button type="primary">点击上传</el-button>
					</zUpload>
				</el-row>
				<div>（选择或上传）</div>
			</el-form-item>
			<el-form-item :label="secdLv.Name" v-if="secdLv.Name">
				<el-input v-if="secdLv.InputType == '0'" v-model="secdLvVal" />
				<el-select v-if="secdLv.InputType == '1'" v-model="secdLvVal" style="width: 100%">
					<el-option v-for="(item, index) in secdLv.Options" :key="index" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item v-for="item in Extends" :key="item.key" :label="item.title">
				<el-input v-model="item.value" />
			</el-form-item>
			<el-form-item label="是否发布">
				<el-switch v-model="curNodeTmp.Status" active-text="是" inactive-text="否" />
			</el-form-item>
			<el-form-item>
				<el-button @click="hideEditFn">取消</el-button>
				<el-button type="primary" @click="submitUpdateNode">确定</el-button>
			</el-form-item>
		</el-form>

		<icons-dialog v-model:iconsVisible="iconsVisible" @select="nodeIcon" @clone="cloneIconsDiag" />
	</div>
</template>

<script lang="js">
// import { Post } from '/@/api/linxyun/base/index.ts';
import zUpload from '/@/components/Linxyun/FileClient/index.vue';
import IconsDialog from '/@/components/Linxyun/IconDialog/IconsDialog.vue';
import FileIns from '/@/components/Linxyun/FileClient/FileClientApi/file_instance.js';
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();

export default {
	components: { zUpload, IconsDialog },
	props: {
		parentNode: {}, // 父节点
		curNode: {}, // 当前节点
		secdLv: {}, // 二级分类
		extend: [], // 扩展字段
		treeType: String,
		operation: String,
		useIcon: Boolean,
		groupID: String,
	},
	data() {
		return {
			secdLvVal: '', // 二级分类内容
			submitUrl: '', // 提交路径
			curCode: '', // 节点编码
			Extends: JSON.parse(JSON.stringify(this.extend)),
			curNodeTmp: null,
			iconsVisible: false,
			fileClient: null,
			attrs: { listType: 'text', limit: 1, drag: false, type: 'img' },
		};
	},
	created() {
		this.curNodeTmp = this.curNode;
		this.secdLvVal = this.curNode.ItemType;
		this.fileClient = FileIns.instance();
		console.log('TreeForm:', this.parentNode, this.curNode, this.treeType);
		if (this.operation == '修改') {
			try {
				for (let i = 0; i < this.Extends.length; i++) {
					for (let j = 0; j < this.curNode.ExtendContent.length; j++) {
						if (this.curNode.ExtendContent[j].key == this.Extends[i].key) {
							this.$set(this.Extends[i], 'value', this.curNode.ExtendContent[j].value);
						}
					}
				}
			} catch (e) {}
		} else {
			this.$set(this.curNodeTmp, 'Status', true);
			let params = { TreeType: this.parentNode.TreeType, SuperiorItemCode: this.parentNode.ItemCode };
			if (this.parentNode.ItemType) {
				params.ItemType = this.parentNode.ItemType;
			}
			httpReqeust.Post(this.parentNode.OpDataInfo.getMaxItemCode, params, null).then((res) => {
				// let maxCode = ''
				if (
					res.Records &&
					res.Records.length > 0 &&
					res.Records[0].MaxCode !== '0' &&
					res.Records[0].MaxCode.length > params.SuperiorItemCode.length
				) {
					// maxCode = res.Recodes[0].MaxCode
					const maxCodeTmp = res.Records[0].MaxCode.substr(params.SuperiorItemCode.length);
					console.log('maxCode:', maxCodeTmp);
					const maxVal = parseInt(maxCodeTmp);
					if (!isNaN(maxVal)) {
						const curCodeTmp = String(maxVal + 1);
						this.curCode = curCodeTmp.padStart(4, '0');
					}
				} else if (res.Records && (res.Records[0].MaxCode === '0' || res.Records[0].MaxCode === '')) {
					this.curCode = '0001';
				} else {
					// this.curCode = '0001'
				}
				console.log(res);
			});
		}
	},
	methods: {
		// 处理需要提交的参数
		async genNodeParams() {
			const params = {};
			params.TreeType = this.treeType;
			switch (this.operation) {
				case '添加':
					params.ItemCode = this.parentNode.ItemCode + this.curCode;
					params.Level = parseInt(this.parentNode.Level) + 1;
					break;
				case '修改':
					params.ItemCode = this.curNode.ItemCode;
					params.Level = this.curNode.Level;
					break;
				default:
					break;
			}
			if (this.secdLvVal) {
				params.ItemType = this.secdLvVal;
			}
			params.Title = this.curNode.Title;
			if (this.curNode.IconID) {
				params.IconID = this.curNode.IconID;
			}
			if (this.groupID) {
				params.GroupID = this.groupID;
			}
			params.SuperiorItemCode = this.parentNode.ItemCode;
			params.Status = this.curNode.Status ? '1' : '0';
			if (this.operation == '添加') {
				params.CreateTime = '_SysTime_';
				if (params.Status === '1') {
					params.PublishTime = '_SysTime_';
				}
			} else {
				if (params.Status === '1') {
					params.PublishTime = '_SysTime_';
				}
			}

			if (this.Extends && this.Extends.length > 0) {
				const tmp = {};
				for (let i = 0; i < this.Extends.length; i++) {
					tmp[this.Extends[i].key] = this.Extends[i].value;
				}

				params.Data = JSON.stringify(tmp);
			}

			await this.uploadIcon();
			params.IconID = this.curNodeTmp.IconID;

			return params;
		},
		// 提交
		async submitUpdateNode() {
			if (this.operation == '添加') {
				var Regx = /^[A-Za-z0-9\._]*$/;
				if (!Regx.test(this.curCode)) {
					this.$message({ message: '节点编码由点，下划线，英文字母或数字组成', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
					return;
				}
				if (this.curCode.length === 0) {
					this.$message({ message: '当前节点编码不能为空', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
					return;
				}
			}

			if (!this.curNode.Title || this.curNode.Title.length <= 0) {
				this.$message({ message: '名称不能为空', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
				return;
			}

			const params = await this.genNodeParams();
			console.log('params', params);
			if (params === null) {
				return;
			}
			if (this.operation == '') return;
			this.operation == '修改'
				? (this.submitUrl = this.parentNode.OpDataInfo.updateFuncName)
				: (this.submitUrl = this.parentNode.OpDataInfo.insertFuncName);
			console.log('[Debug][editNode]update node: ', params);
			const res = await httpReqeust.SyncPost(this.submitUrl, params);
			if (!res || !res.code || res.code !== '0000') {
				this.$message({ message: this.operation + '失败', type: 'error', duration: BASE_API.MSG_SHOW_TIME });
			} else {
				this.$message({ message: this.operation + '成功', type: 'success', duration: BASE_API.MSG_SHOW_TIME });
				this.hideEditFn();
			}
		},
		hideEditFn() {
			this.$emit('hideEditFn');
			this.Extends = [];
		},
		nodeIcon(icon) {
			this.curNodeTmp.IconID = icon;
		},
		async uploadIcon() {
			const fileList = await this.$refs.zupload.uploadSubmit();
			console.log('uploadIcon', fileList);
			fileList.length ? (this.curNodeTmp.IconID = fileList[0].url) : '';
		},
		cloneIconsDiag(){
			this.iconsVisible = false
		}
	},
};
</script>

<style scoped>
:deep(.hide) {
	display: flex;
}
</style>
